package org.myspringframework.beans.factory.support.strategy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.NoOp;
import org.myspringframework.beans.BeansException;
import org.myspringframework.beans.factory.config.beandefinition.BeanDefinition;

import java.lang.reflect.Constructor;

//Cglib实例化
//Cglib代理类获取class需要获取父类的Class
public class CglibSubclassingInstantiationStrategy implements InstantiationStrategy {

    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor ctor, Object[] args) throws BeansException {
        try{

            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(beanDefinition.getBeanClass());
            enhancer.setInterfaces(beanDefinition.getBeanClass().getInterfaces());
            enhancer.setCallback(new NoOp() {
                @Override
                public int hashCode() {
                    return super.hashCode();
                }
            });

            if (null == ctor) return enhancer.create();
            return enhancer.create(ctor.getParameterTypes(), args);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

}